﻿namespace Pibby.Core.IO
{
	using System;
	using System.Collections.Generic;

	public class WellKnownFolders
	{
		public WellKnownFolders()
		{
			this.ListSpecialFolders();
		}

		private List<SpecialFolderPathPair> Folders
		{
			get;
			set;
		}

		private void ListSpecialFolders()
		{
			this.Folders = new List<SpecialFolderPathPair>();

			Type enumType = typeof(Environment.SpecialFolder);

			foreach (var name in Enum.GetNames(enumType))
			{
				this.Folders.Add(new SpecialFolderPathPair(name));
			}
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "untranslated", Justification = "As intended")]
		public string Translate(string untranslated)
		{
			SpecialFolderPathPair match = null;

			foreach (var pair in this.Folders)
			{
				if (!string.IsNullOrEmpty(pair.Path))
				{
					if ((string.Compare(untranslated, pair.Path, StringComparison.OrdinalIgnoreCase) == 0)
						|| untranslated.StartsWith(pair.Path, StringComparison.OrdinalIgnoreCase))
					{
						if (match == null)
						{
							match = pair;
						}
						else
						{
							if (pair.Path.Length > match.Path.Length)
							{
								match = pair;
							}
						}
					}
				}
			}

			if (match != null)
			{
				return untranslated.Replace(match.Path, match.Name);
			}

			return untranslated;
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Untranslate", Justification = "As intended")]
		public string Untranslate(string translated)
		{
			string untranslated = string.Empty;

			foreach (var pair in this.Folders)
			{
				if (!string.IsNullOrEmpty(pair.Path))
				{
					if ((string.Compare(translated, pair.Name, StringComparison.OrdinalIgnoreCase) == 0)
						|| translated.StartsWith(pair.Name, StringComparison.OrdinalIgnoreCase))
					{
						untranslated = translated.Replace(pair.Name, pair.Path);
					}
				}
			}

			if (string.IsNullOrEmpty(untranslated))
			{
				untranslated = translated;
			}

			return untranslated;
		}
	}
}
